<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/3
 * Time: 15:30
 */

namespace app\api\model;

use \Exception;
use think\facade\Db;
use \think\response\Json;

class UserModel
{
    private static $_table = 'user'; // 用户表
    private static $_company = 'company'; // 用户表
    private static $_admin = 'admin'; // 管理员表
    private static $_admin_role = 'role'; // 角色表
    private static $_user_address_table = 'company_address'; // 用户地址表
    private static $_driverTable = 'driver'; // 司机表
    private static $_orderTable = 'order'; // 订单表
    private static $_goodsTable = 'goods'; // 商品表
    private static $_goodsUnitTable = 'goods_unit'; // 商品单位表

    /**用户注册
     * @param array $input
     */
    public static function register($input)
    {
        try {
            $user = Db::table('user')->where('openid', $input['openid'])->field('group_id')->find();
            if ($user['group_id'] != 0) return jsonFail('该商户已经注册,请勿重复注册！');
            Db::startTrans();
            if ($input['role_type'] == 1) {//身份是老板
                $group_id = Db::table('company')->insertGetId(['name' => $input['group_name'], 'create_time' => time(), 'admin_id' => $input['admin_id']]);
            } else {
                $group = Db::table('company')->where('name', $input['group_name'])->find();
                $group_id = $group['id'];
            }
            $pid_user = [];
            if ($input['code']) {//如果填写了邀请码
                $pid_user = Db::table('user')->where('code', $input['code'])->field('id')->find() ? Db::table('user')->where('code', $input['code'])->field('id')->find() : 0;
            }
            $orderSn = substr(microtime(), -6);
            $res = Db::table('user')->where('openid', $input['openid'])->update([
                'group_id' => $group_id,
                'role_type' => $input['role_type'],
                'code' => $orderSn,
                'pid' => $pid_user ? $pid_user['id'] : 0,
                'name' => $input['name'],
                'phone' => $input['phone'],
                'pwd' => sha1($input['pwd']),
            ]);
            if ($res != 0) {
                Db::commit();
                return jsonSuccess('注册成功');
            } else {
                Db::rollback();
                return jsonFail('注册失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('系统错误~', $e->getMessage());
        }
    }

    /**微信注册登录
     * @param array $input
     */
    public static function Wxlogin($input)
    {
        if ($input['code']) {
            require_once '../sdk/WxpayAPI/lib/WxPay.Config.php';
            $appid = \WxPayConfig::APPID;
            $secret = \WxPayConfig::APPSECRET;
            $param["code"] = $input['code'];
            $param["grant_type"] = "authorization_code";
            $param["appid"] = $appid;
            $param["secret"] = $secret;
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?" . http_build_query($param);
            $data = self::curl_url($url);
            if (property_exists($data, 'errcode')) {
                return jsonFail('系统错误', $data);
            } else {
//                if($input['admin_id']=='undefined'){
//                    $input['admin_id']=3;
//                }
                $user_data = self::get_userinfo($data->openid, $data->access_token, $data->refresh_token, $input['state'], $input['admin_id']);
                return jsonSuccess('登录成功', $user_data);
            }
        } else {
            return jsonFail('获取Authorization_Code失败');
        }
    }

    /**用户登录|司机登录
     * @param array $input
     * @return Json
     */
    public static function login($input)
    {
        try {
            switch ($input['type']) {
                case 1://用户
                    $info = Db::table(self::$_table)->alias('a')
                        ->leftJoin(self::$_company . ' b', 'a.group_id = b.id')
                        ->field('a.pwd,a.role_type,a.is_adopt,a.group_id,a.id,a.openid,a.username,a.portrait,a.pid,a.code,a.phone,a.gender,a.integral,a.admin_id,a.status,b.is_believe')
                        ->where('a.phone', $input['phone'])
                        ->where('a.admin_id', $input['admin_id'])
                        ->where('a.status', 1)
                        ->find();
                    break;
                case 2://司机
                    $info = Db::table(self::$_driverTable)
                        ->where('admin_id', $input['admin_id'])
                        ->where('phone', $input['phone'])
                        ->find();
                    break;
                case 3://秤
                    $info = Db::table(self::$_admin)->alias('a')
                        ->leftJoin(self::$_admin_role . ' b', 'a.role_id = b.id')
                        ->where('a.account', $input['account'])
                        ->field('a.type,a.id,a.account,a.name,a.password,a.phone,a.gender,a.status,a.create_time,b.name as role_name')
                        ->find();
                    break;
                default:
                    return jsonFail('类型错误');
            }
            if (empty($info)) return jsonFail('未找到相关人员信息');
            if ($input['type'] == 1) {//用户登录
                $address = Db::table(self::$_user_address_table)->where('group_id', $info['group_id'])->where('is_default', 1)->find();
                $info['company_address'] = $address;
                $center_ids = Db::table('company_center')->where('group_id', $info['group_id'])->field('center_id')->select()->toArray();
                $info['center_ids'] = array_column($center_ids, 'center_id');
                if (sha1($input['pwd']) !== $info['pwd']) return jsonFail('密码不正确');
                $rtn = makeToken('sxb-user', $info['id']);
                if ($rtn == false) return jsonFail('生成登录态失败');
                $info['token'] = $rtn;
                unset($info['pwd']);
                foreach ($info as $k => $v) {
                    if (is_null($v)) unset($info[$k]);
                }
                return jsonSuccess('登录成功', $info);
            } else if ($input['type'] == 2) {//司机登录
                if ($info['status'] != 1) return jsonFail('账号状态出错，请联系管理员处理');
                if (sha1($input['pwd']) !== $info['pwd']) return jsonFail('密码不正确');
                unset($info['pwd']);
                $rtn = makeToken('sxb', 'admin-' . $info['id']);
                if ($rtn == false) return jsonFail('生成登录态失败');
                $info['token'] = $rtn;
                return jsonSuccess('登录成功', $info);
            } else if ($input['type'] == 3) {//秤
                if ($info['status'] != 1) return jsonFail('账号状态出错，请联系管理员处理');
                if (sha1($input['pwd']) !== $info['password']) return jsonFail('密码不正确');
                unset($info['password']);
                $rtn = makeToken('sxb', 'admin-' . $info['id']);
                if ($rtn == false) return jsonFail('生成登录态失败');
                $info['token'] = $rtn;
                return jsonSuccess('登录成功', $info);
            }
        } catch (Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**组合信息
     * @param array $input
     * @return Json
     */
    public static function RemoveUser($info)
    {
        foreach ($info as $key => $value) {
            $data['info']['id'] = $value['id'];
            $data['info']['name'] = $value['name'];
            $data['info']['sex'] = $value['sex'];
            $data['info']['age'] = $value['age'];
            $data['info']['status'] = $value['status'];
            $data['info']['phone'] = $value['phone'];
            $data['info']['create_time'] = $value['create_time'];
            unset($value['phone']);
            unset($value['account']);
            unset($value['name']);
            unset($value['sex']);
            unset($value['age']);
            unset($value['status']);
            unset($value['create_time']);
            unset($value['pwd']);
            unset($value['id']);
            $data['children'][] = $value;
        }
        return $data;
    }

    //微信授权回调根据Access_token获取指定用户信息
    public static function get_userinfo($openid, $access_token, $refresh_token, $state, $admin_id)
    {
        if ($access_token) {
            $param["openid"] = $openid;
            $param["access_token"] = $access_token;
            $url = "https://api.weixin.qq.com/sns/userinfo?" . http_build_query($param);
            $data = self::curl_url($url);
            return self::logins($data->sex, $data->openid, $data->nickname, $data->headimgurl, $access_token, $refresh_token, $state, $admin_id);
        }
    }

    //获取配置信息
    public static function logins($gender, $userid, $uname, $portrait, $access_token, $refresh_token, $state, $admin_id)
    {
        $data['openid'] = $userid;   // 账号参数
        $data['username'] = $uname;   // 用户名
        $data['portrait'] = $portrait;   // 头像访问
//        $data['access_token'] = $access_token;   // access_token码，一个月有效期
//        $data['refresh_token'] = $refresh_token;//access_token码过期后，刷新码，10年有效期
        $user_data = Db::table('user')->alias('a')
            ->where('a.openid', $userid)
            ->field('a.role_type,a.is_adopt,a.group_id,a.id,a.openid,a.username,a.portrait,a.pid,a.code,a.phone,a.gender,a.integral,a.admin_id,a.status')
            ->find();
        if (empty($user_data)) {
            $pid_user = [];
            if ($state) {//如果填写了邀请码
                $pid_user = Db::table('user')->where('code', $state)->find();
            }
            $orderSn = substr(microtime(), -6);
            $res = Db::table('user')->insertGetId([
                'pid' => $pid_user ? $pid_user['id'] : 0,
                'code' => $orderSn,
                'admin_id' => $admin_id,
                'openid' => $userid,
                'username' => $uname,
                'gender' => $gender,
                'portrait' => $portrait,
                'access_token' => $access_token,
                'refresh_token' => $refresh_token,
                'create_time' => time(),
            ]);
            return $data;
        } else {
            return $data;
        }
    }

    /**获取员工列表
     * @return Json
     */
    public static function EmployeeList($input)
    {
        $list = Db::table(self::$_table)->where('group_id', $input['group_id'])->where('role_type', 2)->where('status', 1)->field('id,portrait,name,phone,is_adopt')->select()->toArray();
        return jsonSuccess('获取成功', $list);
    }

    /**老板审核员工
     * @return Json
     */
    public static function IsAdopt($input)
    {
        $boss = Db::table(self::$_table)->where('id', $input['uid'])->where('status', 1)->where('role_type', 1)->value('is_adopt');
        if (empty($boss)) return jsonFail('暂无老板身份信息');
        if ($boss != 1) return jsonFail('老板身份暂未通过审核');
        $res = Db::table('user')->where('id', $input['id'])->update(['is_adopt' => $input['is_adopt']]);
        if ($res) return jsonSuccess('审核成功');
        return jsonFail('审核失败');
    }

    /**
     * @desc 老板解除员工
     * @return Json
     */
    public static function RelieveEmployee($input)
    {
        Db::startTrans();
        try {
            $res = Db::table('user')->where('id', $input['id'])->update(['is_adopt' => 2,
                'group_id' => 0,
                'role_type' => 0
            ]);
            if ($res) {
                Db::commit();
                return jsonSuccess('解绑成功');
            } else {
                Db::rollback();
                return jsonFail('解绑失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * @desc 员工重新绑定
     * @return Json
     */
    public static function ChoiceCompany($input)
    {
        Db::startTrans();
        try {
            if ($input['role_type'] == 1) {//身份是老板
                $group_id = Db::table('company')->insertGetId(['name' => $input['group_name'], 'create_time' => time()]);
            } else {
                $group = Db::table('company')->where('name', $input['group_name'])->find();
                $group_id = $group['id'];
            }
            $res = Db::table('user')->where('openid', $input['openid'])->update([
                'group_id' => $group_id,
                'role_type' => $input['role_type']
            ]);
            if ($res) {
                Db::commit();
                return jsonSuccess('绑定成功');
            } else {
                Db::rollback();
                return jsonFail('绑定失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('公司名字不能重复~');
        }
    }

    /**
     * @desc 获取用户基本信息
     * @return Json
     */
    public static function UserInfo($input)
    {
        $data = Db::table('user')->alias('a')
            ->leftJoin(self::$_company . ' b', 'a.group_id = b.id')
            ->where('a.openid', $input['openid'])->field('a.role_type,a.is_adopt,a.group_id,a.id,a.openid,a.username,a.portrait,a.pid,a.code,a.phone,a.gender,a.integral,a.admin_id,a.status,b.is_believe')
            ->find();
        $center_ids = Db::table('company_center')->where('group_id', $data['group_id'])->field('center_id')->select()->toArray();
        $data['center_ids'] = array_column($center_ids, 'center_id');
        return jsonSuccess('获取成功', $data);
    }

    //curl进行Https Get访问链接
    public static function curl_url($url)
    {
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $output = curl_exec($ch); //执行并获取HTML文档内容
        $data = json_decode($output);
        //释放curl句柄
        curl_close($ch);
        return $data;
    }

    /**用户查看下单统计
     * @param $input
     * @return Json
     */
    public static function OrderStatistics($input)
    {
        try {
            $map = [
                ['group_id','=', $input['group_id']],
                ['status', 'not in', '-2,-3,-4'],
            ];
            $data = Db::table(self::$_orderTable)
                ->field('distinct goods_data,sum(num) as total_num')
                ->where($map)
                ->group('goods_id')
                ->select()->toArray();
            $list = [];
            foreach ($data as $v) {
                $goods_data = json_decode($v['goods_data'], true);
                $list[] = [
                    'goods_id' => $goods_data['id'],
                    'total_num' => $v['total_num'],
                    'img' => $goods_data['image'],
                    'goods_name' => $goods_data['name'],
                    'goods_unit' => $goods_data['unit_name']
                ];
            }
            return jsonSuccess('获取成功',$list);
        }catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}